define('apps/common/MailPublisher', ['core/jQuery', 'apps/common/AtSuggestion', 'core/SWFUpload', 'core/Publisher', 'apps/Face/FaceBox'], function(require) {

    var $ = require('core/jQuery'),
        AtSuggestion = require('apps/common/AtSuggestion'),
        SWFUpload = require('core/SWFUpload'),
        Publisher = require('core/Publisher'),
        FaceBox = require('apps/Face/FaceBox'),

        queueErr = SWFUpload.QUEUE_ERROR,
        uploadErr = SWFUpload.UPLOAD_ERROR,
        ErrTip = {},
        lang = 'ch',
        Word = {
            /*----- 附件上传错误信息  ----*/
            'MAIL_FILE_EMPTY' : {
                'ch':'图片文件为空文件'
            },
            'MAIL_FILE_SIZE_LIMIT' : {
                'ch':'图片大小不能超过30M'
            },
            'MAIL_FILE_NUM_LIMIT' : {
                'ch':'最多只能上传10个附件'
            },
            'MAIL_FILE_TYPE_INVALID' : {
                'ch':'图片格式错误'
            },
            'MAIL_UPLOAD_NETWORK_ERR' : {
                'ch':'网络传输错误，请检查网络连接'
            },
            'MAIL_UPLOAD_NUM_LIMIT' : {
                'ch':'上传图片过多'
            },
            'MAIL_UPLOAD_FAIL' : {
                'ch':'上传失败'
            }
        },

        URL = {
            'picupload' : 'http://'+K.Env.wwwHost+'/chat/ajax/file_upload.php'
        },

        TPL = {
            'attachItem' : '<div class="file_tips fix  _j_attachitem _j_swf_{{=it.id}}">\
                                <div class="progress l _j_attachprocess"><div style="width:0" class="progress_percent"></div></div>\
                                <span title="{{=it.title}}" class="c9 _j_attachname dn">{{=it.name}}</span>\
                                <a class="spr_icons i_close r _j_del abs" data-fid="{{=it.id}}" data-index="{{=it.index}}" href="#"></a>\
                            </div>'
        },

        IMG_URL = {
            'enabled' : 'http://{_IMG_HOST_}/pici/flash_upfile.png',
            'disabled' : 'http://{_IMG_HOST_}/pici/flash_upfile_dis.png'
        },

        MailPublisher = K.extend(function(opts) {
            this.attachBtnID = opts.attachBtnID;
            this.attachContainer = opts.attachContainer;
            this.faceTrigger = opts.faceTrigger;
            this.strangerMode = opts.strangerMode;
            MailPublisher.$super.call(this, opts);
            this.attachments = {};
            this.fileQueued = {};
            this.swfLoaded = false;
            this.preSetStrangerMode = false;

            K.CustEvent.createEvents(this, 'mailpublisher:uploadfinish');

            this.initSelf();
        }, Publisher);

    ErrTip[queueErr.ZERO_BYTE_FILE] = Word['MAIL_FILE_EMPTY'][lang];
    ErrTip[queueErr.FILE_EXCEEDS_SIZE_LIMIT] = Word['MAIL_FILE_SIZE_LIMIT'][lang];
    ErrTip[queueErr.QUEUE_LIMIT_EXCEEDED] = Word['MAIL_FILE_NUM_LIMIT'][lang];
    ErrTip[queueErr.INVALID_FILETYPE] = Word['MAIL_FILE_TYPE_INVALID'][lang];
    ErrTip[uploadErr.HTTP_ERROR] = Word['MAIL_UPLOAD_NETWORK_ERR'][lang];
    ErrTip[uploadErr.IO_ERROR] = Word['MAIL_UPLOAD_NETWORK_ERR'][lang];
    ErrTip[uploadErr.SECURITY_ERROR] = Word['MAIL_UPLOAD_FAIL'][lang];
    ErrTip[uploadErr.UPLOAD_LIMIT_EXCEEDED] = Word['MAIL_FILE_NUM_LIMIT'][lang];
    ErrTip[uploadErr.UPLOAD_FAILED] = Word['MAIL_UPLOAD_FAIL'][lang];
    ErrTip[uploadErr.FILE_VALIDATION_FAILED] = Word['MAIL_UPLOAD_FAIL'][lang];
    ErrTip[uploadErr.FILE_CANCELLED] = Word['MAIL_UPLOAD_FAIL'][lang];
    ErrTip[uploadErr.UPLOAD_STOPPED] = Word['MAIL_UPLOAD_FAIL'][lang];

    K.mix(MailPublisher.prototype, {

        'initSelf' : function() {

            // init at
            //new AtSuggestion({'area' : this.pubArea});

            // init facebox
     		new FaceBox({'trigger' : this.faceTrigger, 'area' : this.pubArea});

			$('#'+this.attachBtnID).parent('a').click(function(ev) { ev.preventDefault(); });

            // init attachment upload
            this.initAttachmentUpload();
        },

        'initAttachmentUpload' : function() {
            this.attachContainer.delegate('._j_del', 'click', $.proxy(this.deleteAttachItem, this));
            this.attachUploader = new SWFUpload({
                flash_url : 'http://{_IMG_HOST_}/swf/swfupload.swf',
                upload_url: URL.picupload,
                file_post_name: 'file',
                file_size_limit : '30 MB',
                file_types : '*.*',
                file_types_description : '文件',
                file_upload_limit : 10,
                file_queue_limit : 0,

                // Button settings
                button_image_url: this.strangerMode ? IMG_URL.disabled : IMG_URL.enabled,
                button_width: '21',
                button_height: '21',
                button_placeholder_id: this.attachBtnID,
                button_window_mode: 'transparent',
                button_disabled: this.strangerMode ? true : false,
                button_cursor : this.strangerMode ? SWFUpload.CURSOR.ARROW : SWFUpload.CURSOR.HAND,

                // handler setting
                swfupload_loaded_handler : $.proxy(this.swfuploadLoaded, this),
                file_queued_handler :  $.proxy(this.fileQueueHandler, this),
                file_dialog_complete_handler : $.proxy(this.fileDialogCompleteHandler, this),
                file_queue_error_handler : $.proxy(this.errHandler, this),
                upload_start_handler : $.proxy(this.uploadStartHandler, this),
                upload_progress_handler : $.proxy(this.uploadProgressHandler, this),
                upload_error_handler : $.proxy(this.errHandler, this),
                upload_success_handler : $.proxy(this.uploadSuccessHandler, this),
                upload_complete_handler : $.proxy(this.uploadCompleteHandler, this)
            });
        },

        'swfuploadLoaded' : function() {
            var param = {};
            param._kxcuser = Cookie.get('_kxcuser');
            this.attachUploader.setPostParams(param);

            // set strange mode
            this.swfLoaded = true;
            try {
                $('#'+this.attachUploader.movieName).attr('tabindex', '-1');
            } catch(e) { K.log(e) }
        },
        'fileQueueHandler' : function(file) {
            if(!this.isDuplicate(file)) {
                this.attachContainer.append(this.createAttachItem(file)).show();
            } else {
                this.attachUploader.cancelUpload(file.id, false);
                this.showErrTip(file.name+'已经存在，请不要重复上传！');
            }
        },
        'fileDialogCompleteHandler' : function(file) {
            this.attachUploader.startUpload();
        },
        'errHandler' : function(file, errno) {
            var errmsg = ErrTip[errno];
            this.showErrTip(errmsg);
        },
        'uploadStartHandler' : function() {
            this.attachContainer.removeClass('dn');
            this.pubButton.addClass('disabled');
        },
        'uploadProgressHandler' : function(file, uploaded, total) {
            var processItem = this.attachContainer.find('._j_swf_'+file.id);
            processItem.children('._j_attachprocess').children().animate({
                'width' : Math.ceil((uploaded/total)*100)+'%'
            }, 200);
        },
        'uploadSuccessHandler' : function(file, data) {
            var processItem = this.attachContainer.find('._j_swf_'+file.id);
            data = $.parseJSON(data);
            if(!data.error && data.payload) {
                var data = data.payload;
                this.attachments[file.id] = data.fileid;
                processItem.children('._j_attachprocess').addClass('dn');
                processItem.children('._j_attachname').removeClass('dn');

                // 检测队列是否上传完毕
                if(this.attachUploader.getStats().files_queued == 0) {
                    this.fire('mailpublisher:uploadfinish');
                    this.pubButton.removeClass('disabled');
                }
            } else {
                K.log('Data Err:', data);
            }
        },
        'uploadCompleteHandler' : function() {
            if(this.attachUploader.getStats().files_queued > 0) {
                this.attachUploader.startUpload();
            }
        },
        'isInUploadding' : function() {
            return this.attachUploader.getStats().files_queued > 0;
        },
        'createAttachItem' : function(file) {
            return doT.template(TPL.attachItem)({'name':K.subByte(file.name, 23, '...'), 'title':file.name, 'id':file.id, 'index':file.index});
        },
        'deleteAttachItem' : function(ev) {
            var $target = $(ev.currentTarget),
                fileID = $target.data('fid'),
                index = $target.data('index');

            var fileStatus = this.attachUploader.getFile(index).filestatus;

            // 根据文件状态，来删除其在已上传中的状态
            if(fileStatus === SWFUpload.FILE_STATUS.COMPLETE) {
                var stats = this.attachUploader.getStats();
                stats.successful_uploads--;
                this.attachUploader.setStats(stats);
            }

            this.attachUploader.cancelUpload(fileID, false);

            delete this.attachments[fileID];
            delete this.fileQueued[fileID];
            $target.closest('._j_attachitem').remove();
            if(!this.attachContainer.children('._j_attachitem').length) {
            	this.attachContainer.hide();
            }

            // 检测队列是否上传完毕
            if(this.attachUploader.getStats().files_queued == 0) {
                this.fire('mailpublisher:uploadfinish');
                this.pubButton.removeClass('disabled');
            }
            ev.preventDefault();
        },
        'isDuplicate' : function(file) {
            var qfile;
            for(var i in this.fileQueued) {
                if(this.fileQueued.hasOwnProperty(i)) {
                    qfile = this.fileQueued[i];
                    if(qfile.name === file.name && qfile.size === file.size) {
                        return true;
                    }
                }
            }
            this.fileQueued[file.id] = file;
            return false;
        },

        'showErrTip' : function(errmsg) {
            var errCnt = this.attachContainer.next('._j_uploaderrcnt');

            // 获得显示错误信息的dom
            if(!errCnt) {
                errCnt = $('<span class="ui_error abs _j_uploaderrcnt"></span>').after(this.attachContainer);
            }

            errCnt.text(errmsg).show();
        },

        'reset' : function() {
            this.fileQueued = {};
            try {
                this.attachUploader.setStats({
                    in_progress : 0,
                    files_queued : 0,
                    successful_uploads : 0,
                    upload_errors : 0,
                    upload_cancelled : 0,
                    queue_errors : 0
                });
            } catch(e) {}
            this.attachContainer.css('height', 'auto').next('._j_uploaderrcnt').hide();
            this.pubArea.val('');
            this.attachContainer.empty();
            this.attachments = {};
        }

    });

    return MailPublisher;

});

